<?php
namespace Addons\Forms\Controller;
class IndexController extends \Addon
{
    public function __construct()
    {
        parent::__construct();
        $this->FieldsdisplayType = dict("FieldsdisplayType");
        $this->model = BoxModel('addon_fields');

    }

    /**
     * 表单列表
     * @return
     */

    public function index()
    {
        $this->admin_display();
    }


    /**
     * 字段列表
     * @return
     */
    public function fields()
    {
        $this->group_name = I('group_name');
        $this->data = $this->model->get("group_name='" . urldecode($this->group_name) . "'", "", "order_by");
        //dump($this->model);
        $this->admin_display();
    }

    /**
     * 添加字段
     */
    public function add()
    {
        $this->group_name = I('group_name', "", "urldecode");
        $id = I('id');
        if (IS_POST) {
            $row = $this->model->create();
												$row['tip']=stripslashes(htmlspecialchars_decode(I('tip')));
            if ($id) {
                $this->model->where(array('id' => $id))->save($row);
            } else {
                $id = $this->model->add($row);
            }
            $this->jump("保存成功", addons_url('fields', array('group_name' => $this->group_name)));
        }
        if ($id) {
            $this->data = $this->model->find($id);
												//$data['tip']=str_replace('data-type="modal"','target="modal"',$data['tip']);
            $this->group_name = $this->data['group_name'];
        }
        $this->admin_display();
    }

    /**
     * 分类
     * @return [type] [description]
     */
    public function del()
    {
        $id = I('id');
        if ($id) {
            $data = $this->model->where("id='$id'")->find();
            $this->model->delete($id);
            $this->jump("删除成功", addons_url('fields', array('group_name' => $data['group_name'])));
        }
    }

    public function  displayFormGroupHtml($param){
					 $this->param=$param;
					 $group = $param['group'];
						$this->formsData=BoxModel("addon_forms")->get(array('group'=>$group),"","order_by");
						$this->display();
				}
    public function  displayFormHtml($param)
    {
        //dump($param);
								$this->formParam=$param;
        $group_name = $param['group_name'];
        $values = (array)$param['values'];
        $data = BoxModel("addon_fields")->get("group_name='$group_name'", "", "order_by");
        $html = "";
        foreach ($data as $k => $one) {
            $html .= $this->getAttrHtml($one, $values[$one['fieldName']], $param['display']);
        }
								$this->html=$html;
								//dump($this->html);
								$this->display("Forms/Index/displayFormHtml");
       //echo $html;
    }

    public function getItem($catItem)
    {
        $catItem=stripslashes(htmlspecialchars_decode($catItem));
								if (!$catItem) return $catItem;
        $bool = false;
        /****字典中读取数据*/
        if (strpos($catItem, "php") === 0) {
									 // echo 123123;
										  
            $str = trim(str_replace("php|", "", $catItem),";").";";
												//dump($str);exit();
            eval($str);
            $bool = true;
        }

        if ($bool) {
            $catItems = array();
            foreach ($catItem as $k => $v) $catItems[] = $k . "|" . $v;
            $catItem = implode(",", $catItems);
            return $catItem;
        } else {
            return $catItem;
        }

    }

    public function getAttrHtml($attr, $offerValue = null, $display = "horizontal")
    {

        $attr["catItem"] = $this->getItem($attr["catItem"]);//选项
        $type = $attr['displayType'];
        if ($offerValue) {
            $value = $offerValue;
        } else {
            if ($attr["defaultValue"]) {
                //dump(stripslashes(htmlspecialchars_decode($attr['defaultValue'])));
                $value = $this->fetch("", stripslashes(htmlspecialchars_decode($attr['defaultValue'])));
            }
        }
								$tip="";
								if($attr["tip"]){
									$tip="<p class='form-group-tip'>".$attr["tip"]."</p>";
								}
        $IsDisplay = "";
        if ($attr['IsDisplay'] != 1) {
            $IsDisplay = 'style="display:none"';
        }
        $htmlstr = "";
        $left = '<div class="form-group attr-its" ' . $IsDisplay . '  for="' . $attr["fieldName"] . '">';
        if ($display == "horizontal") {
            $class = "class='col-sm-2 control-label'";
        }
        $left .= '<label for="' . $attr["fieldDisplay"] . '" ' . $class . '>';
        $noEmpty = '';
        $validate = '';
        if ($attr["IsNeed"] == 1) {
            $left .= '<span class="require">*</span>';
            $noEmpty = 'required';
        }
        if ($attr["valueType"] == 'none') {
           $validate = "";

        }else if($attr["valueType"] == 'phone'){
									 $validate = 'data-bv-'.$attr["valueType"].' data-bv-phone-country=\'CN\' ';
								}else{
									 $validate = 'data-bv-'.$attr["valueType"].' ';
								}
        $left .= $attr["fieldDisplay"];
        $left .= ' </label>';
        if ($display == "horizontal") {
            $left .= '<div class="col-sm-7">';
        }
								if($attr['readonly']==1){
									 $readonly="readonly";
								}
        switch ($type) {
            case "1"://单行文本
                $maxLength = '';
                if ($attr["fieldLen"]) {
                    $maxLength = 'maxlength=' . $attr["fieldLen"];
                }
                if ($attr["unit"] || $attr["fieldPrefix"]) {
                    $htmlstr .= '<div class="input-group">';
                }
                if ($attr["fieldPrefix"]) {
                    $htmlstr .= '<div class="input-group-addon">' . $attr["fieldPrefix"] . '</div>';
                }

                $htmlstr .= "<input ".$readonly." placeholder='" . $attr['fieldDes'] . "' class='form-control cat-attr ipt-lg' type=\"text\" name=\"" . $attr["fieldName"] . "\" id=\"" . $attr["fieldName"] . "\" value=\"" . $value . "\"" . $maxLength . " " . $noEmpty . " " . $validate . ">";
                $htmlstr.=$tip;
                if ($attr["unit"]) {
                    $htmlstr .= '<div class="input-group-addon"><span class="aunit">' . $attr["unit"] . '</span></div>';
                }
                if ($attr["unit"] || $attr["fieldPrefix"]) {
                    $htmlstr .= '</div>';
                }
                break;

            case "2"://多行文本
                $htmlstr = "<textarea ".$readonly."  placeholder='" . $attr['fieldDes'] . "' class='form-control cat-attr ipt-lg' name=\"" . $attr["fieldName"] . "\" id=\"" . $attr["fieldName"] . "\" cols=\"70\" rows=\"15\" " . $noEmpty . ">" . $value . "</textarea>";
                $htmlstr.=$tip;
															 break;


            case "3"://下拉框
                $selectnum = "<select class='form-control cat-attr ipt-lg' id=\"" . $attr["fieldName"] . "\" name=\"" . $attr["fieldName"] . "\" " . $noEmpty . ">";
                $numarray = explode(",", $attr["catItem"]);
                for ($ii = 0; $ii < count($numarray); $ii++) {
                    $itemvalue = explode("|", $numarray[$ii]);//.split('|');
                    if ($itemvalue[0] == $value) {
                        $selectnum .= "<option value=\"" . $itemvalue[0] . "\" selected>" . $itemvalue[1] . "</option>";
                    } else {
                        $selectnum .= "<option value=\"" . $itemvalue[0] . "\">" . $itemvalue[1] . "</option>";
                    }
                }
                $selectnum .= "</select>";
                $htmlstr = $selectnum;
																$htmlstr.=$tip;
                break;


            case "4"://单选框
                $selectnum = "";
                $numarray = explode(",", $attr["catItem"]);//value.split(',');
                for ($ii = 0; $ii < count($numarray); $ii++) {
                    $itemvalue = explode("|", $numarray[$ii]);//.split('|');
                    if ($itemvalue[0] == $value) {
                        $selectnum .= "<label class=\"radio-inline\"><input class='radio cat-attr' type=\"radio\" name=\"" . $attr["fieldName"] . "\" id=\"" . $attr["fieldName"] . "\" value=\"" . $itemvalue[0] . "\" checked " . $noEmpty . ">" . $itemvalue[1] . '</label>';
                    } else {
                        $selectnum .= "<label class=\"radio-inline\"><input class='radio cat-attr' type=\"radio\" name=\"" . $attr["fieldName"] . "\" id=\"" . $attr["fieldName"] . "\" value=\"" . $itemvalue[0] . "\" " . $noEmpty . ">" . $itemvalue[1] . '</label>';
                    }
                }
                $htmlstr = $selectnum;
																$htmlstr.=$tip;
                break;

            case "5"://多选框
                $selectnum = "";
                $numarray = explode(",", $attr["catItem"]);//value.split(',');
                for ($ii = 0; $ii < count($numarray); $ii++) {
                    $itemvalue = explode("|", $numarray[$ii]);//.split('|');
                    if (is_array($value)) {
                        $nv = $value;
                    } else {
                        $nv = explode(",", $value);
                    }
                    if (in_array($itemvalue[0], $nv))
                        $str = "checked";
                    else
                        $str = '';
                    $selectnum .= "<label class=\"checkbox-inline\"><input class='checkbox cat-attr' $str type=\"checkbox\" name=\"" . $attr["fieldName"] . "[]\" id=\"" . $attr["fieldName"] . "[]\" value=\"" . $itemvalue[0] . "\" " . $noEmpty . ">" . $itemvalue[1] . '</label>';
                }
                $htmlstr = $selectnum;
																 $htmlstr.=$tip;
                break;
            case "6"://多选框
                if (empty($value)) {
                    $value['min'] = '';
                    $value['max'] = '';
                }
                $maxLength = '';
                if ($attr["fieldLen"]) {
                    $maxLength = 'maxlength=' . $attr["fieldLen"];
                }
                $htmlstr .= '<div class="input-group">';
                $htmlstr .= "<input class='form-control cat-attr ipt-sm' type=\"text\" name=\"" . $attr["fieldName"] . "[min]\" id=\"" . $attr["fieldName"] . "[min]\" value=\"" . $value['min'] . "\"" . $maxLength . " " . $noEmpty . " " . $validate . ">";
                if ($attr["unit"]) {
                    $htmlstr .= '<div class="input-group-addon"><span class="to">到</span></div>';
                }
                $htmlstr .= "<input class='form-control cat-attr ipt-sm' type=\"text\" name=\"" . $attr["fieldName"] . "[max]\" id=\"" . $attr["fieldName"] . "[max]\" value=\"" . $value['max'] . "\"" . $maxLength . " " . $noEmpty . " " . $validate . ">";
                if ($attr["unit"]) {
                    $htmlstr .= '<div class="input-group-addon"><span class="aunit">' . $attr["unit"] . '</span></div>';
                }
                $htmlstr .= '</div>';
																 $htmlstr.=$tip;
                break;

            case "7"://上传控件
                $htmlstr = "<input onchange='var o=$(this).val();var pos=o.lastIndexOf(\"\\\\\");var name=o.substring(pos+1);name==\"\"?$(this).next().val($(this).next().attr(\"data-value\")):$(this).next().val(name);var field=$(this).next().attr(\"name\");$(this).parents(\"form\").bootstrapValidator(\"updateStatus\", field, \"NOT_VALIDATED\").bootstrapValidator(\"validateField\", field);'  type='file'  placeholder='" . $attr['fieldDes'] . "' class='form-control cat-attr ipt-lg' name=\"" . $attr["fieldName"] . "\" id=\"" . $attr["fieldName"] . "\" >";
                $htmlstr.=' <input type="hidden" '.$noEmpty . " " . $validate .' name="'.$attr["fieldName"].'_hidden" data-value="'.$value['file_name'].'" value="'.$value['file_name'].'" />';
															 $htmlstr.=$tip;
															 if ($value) {
																				$htmlstr.=' <input type="hidden" '.$noEmpty . " " . $validate .' name="'.$attr["fieldName"].'[file_url]" value="'.$value['file_url'].'" />';
																				$htmlstr.=' <input type="hidden" '.$noEmpty . " " . $validate .' name="'.$attr["fieldName"].'[file_name]" value="'.$value['file_name'].'" />';
																				$p=explode(".",$value['file_url']);
																				$ext=$p[count($p)-1];
																				//dump(strtolower($ext));
																				if(in_array(strtolower($ext),array('jpg','png','bmp','gif','jpeg'))){
																				 $htmlstr.='<p class=""><img data-type="photoBrowser" width="200" src="'.ImgDomain."/".$value['file_url'].'"></p>';
																				}
																				$htmlstr.='<p><a data-type="none" href="'.ImgDomain."/".$value['file_url'].'" target="_blank">'.$value['file_name'].'</a></p>';
                }
																break;
																
																
            case "8"://多文件上传控件
                $catItem = array();
                if ($attr['catItem']) {
                    $value_str = str_replace("Array", "array", stripslashes(htmlspecialchars_decode($attr['catItem'])));
                    eval("\$catItem = " . $value_str . '; ');
                }
                $param = array(
                    'exts' => $catItem['exts'],//上传的文件类型
                    'allowEdit' => $catItem['allowEdit'],
                    'inputName' => $attr["fieldName"],//上传之后数据保存在textarea
                    'value' => $value,
                );
                $htmlstr = "<div>" . $attr['fieldDes'] . "</div>";
                $htmlstr .= uploadAddon($param, 1);
                break;
												 case "9"://smarty html
											 	//	dump($attr["catItem"]);
													   if($attr["catItem"]){
                	$htmlstr = $this->fetch("",$attr["catItem"]);
																}
																break;				
        }
        $right = '</div>';
        if ($display == "horizontal") {
            $right .= "</div>";
        }
        return $left . $htmlstr . $right;
    }

    public function viwe()
    {
        $this->group_name = urldecode(I('group_name'));
        $this->admin_display();

    }
				
				public function formFields($form_name){
			   $data = BoxModel("addon_fields")->get("group_name='$form_name'", "", "order_by");		
					 $Fields=array();
						foreach($data as $one){
							 $Fields[$one['fieldName']]=$one['fieldDisplay'];
						}
						return (array)$Fields;
			}
			
			
			public function formGroupFields($group_name){
			   $data = BoxModel("addon_forms")->get(array('group'=>$group_name),"","order_by");
						$Fields=array();
					 foreach($data as $one){
							$form_name=$one['name'];
							$row=$this->formFields($form_name);
							$Fields=array_merge($Fields,$row);
						}
					
						return (array)$Fields;
			}
			
			


}